/**
 * Created by Administrator on 2017/4/6.
 */
/**
 * Created by neal on 11/22/16.
 */

var Config = {
    createUrl: '/api/goods',
    updateUrl: '/api/goods',
    deleteUrl: '/api/goods',
    selectUrl: '/api/goods',
    selectCompanyUrl: '/api/admin/company/providers',
};

var ConfigCategory = {
    createUrl: '/api/admin/categories/post',
    updateUrl: '/api/admin/categories/update',
    deleteUrl: '/api/admin/categories/delete',
    selectUrl: '/api/admin/categories/get'
};

var ConfigType = {
    createUrl: '/api/admin/goodsType/post',
    updateUrl: '/api/admin/goodsType/update',
    deleteUrl: '/api/admin/goodsType/delete',
    selectUrl: '/api/admin/goodsType/get'
};

var ConfigAttribute = {
    selectUrl: '/api/goodsAttribute'
};
var ConfigAttributeLink = {
    createUrl: '/api/goodsAttributeLink',
}


$.validator.setDefaults({
    highlight: function (e) {
        $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
    }, success: function (e) {
        e.closest(".form-group").removeClass("has-error").addClass("has-success");
    }, errorElement: "span", errorPlacement: function (e, r) {
        e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
    }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
});

var ue = UE.getEditor('editor');
var ueAlbum = UE.getEditor('editorAlbum');

$().ready(function () {

    $("#datepicker").datepicker({keyboardNavigation: !1, forceParse: !1, autoclose: !0});
    $.ajax(
        {
            url: ConfigCategory.selectUrl,
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="0" hassubinfo="true">顶级分类</option>');
                data.data.map(function (category) {
                    categories.push('<option value="');
                    categories.push(category.categoryId);
                    categories.push('" ');
                    categories.push('hassubinfo="true">');
                    categories.push(category.categoryName);
                    categories.push('</option>');
                });
                $("#categoryId").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
    $.ajax(
        {
            url: ConfigType.selectUrl,
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="0" hassubinfo="true"  >商品类型</option>');
                data.data.map(function (category) {
                    categories.push('<option value="');
                    categories.push(category.typeId);
                    categories.push('" ');
                    categories.push('hassubinfo="true">');
                    categories.push(category.typeName);
                    categories.push('</option>');
                });
                $("#typeId").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });

    $.ajax(
        {
            url: ConfigCategory.selectUrl,
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="0" hassubinfo="true">顶级分类</option>');
                data.data.map(function (category) {
                    categories.push('<option value="');
                    categories.push(category.categoryId);
                    categories.push('" ');
                    categories.push('hassubinfo="true">');
                    categories.push(category.categoryName);
                    categories.push('</option>');
                });
                $("#goodsBrandId").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });

    // providers
    $.ajax(
        {
            url:'/api/admin/companyInfo',
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data) {
                var goodsProviders = [];
                goodsProviders.push('<option value="0" hassubinfo="true">顶级分类</option>');
                data.data.map(function (goodsProvider) {
                    goodsProviders.push('<option value="');
                    goodsProviders.push(goodsProvider.companyId);
                    goodsProviders.push('" ');
                    goodsProviders.push('hassubinfo="true">');
                    goodsProviders.push(goodsProvider.companyName);
                    goodsProviders.push('</option>');
                });
                $("#goodsProviderId").html(goodsProviders.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error(errorThrown);
            }
        }
    );

    jQuery.validator.addMethod('selectcheck', function (value) {
        return (value != '0');
    }, "请选择分类");
    $('#submitGoodsCreate').click(function () {
        $("#ajaxform").validate({
            rules: {
                categoryId: {
                    selectcheck: true
                }
            }
        });
        // var oneLevel=Number($("input[id=oneLevel]").val());
        // var twoLevel=0;
        // var areaLevel=0;
        // var cityLevel=0;
        // var provinceLevel=0;
        // var rtLevel=0;
        // var twoLevel=Number($("input[id=twoLevel]").val());
        // var areaLevel=Number($("input[id=areaLevel]").val());
        // var cityLevel=Number($("input[id=cityLevel]").val());
        // var provinceLevel=Number($("input[id=provinceLevel]").val());
        // var rtLevel=Number($("input[id=rtLevel]").val());
        // if (oneLevel + twoLevel + areaLevel + cityLevel + provinceLevel > 100 || oneLevel + twoLevel + areaLevel + cityLevel + provinceLevel + rtLevel < 0){
        //     toastr.success("请正确输入比例");
        //     return false;
        // }
        if ($('#ajaxform').valid()) {
            var postData = $('#ajaxform').serializeArray();
            console.log(postData);
            $.ajax(
                {
                    url: Config.createUrl,
                    type: "POST",
                    data: postData,
                    dataType: "json",
                    success: function (data, textStatus, jqXHR) {
                        CONST_GLOBAL_GOODS_ID = data.data.goodsId;
                        // $.ajax({
                        //     url:"/api/admin/rebateRatio",
                        //     type: "POST",
                        //     data: {goodsId:CONST_GLOBAL_GOODS_ID,oneLevel:oneLevel,twoLevel:twoLevel,
                        //         areaLevel:areaLevel,cityLevel:cityLevel,provinceLevel:provinceLevel,rtLevel:rtLevel},
                        //     dataType: "json",
                        //     success: function (data, textStatus, jqXHR) {
                        //         toastr.success("返利比例创建成功!", data.title);
                        //     }
                        // });
                        ue.ready(function () {
                            ue.execCommand('serverparam', {
                                'goodsId': CONST_GLOBAL_GOODS_ID,
                                'imageType': 0
                            });
                        });
                        ueAlbum.ready(function () {
                            ueAlbum.execCommand('serverparam', {
                                'goodsId': CONST_GLOBAL_GOODS_ID,
                                'imageType': 1
                            });
                        });
                        toastr.success(data.msg, data.title);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        toastr.error(errorThrown, textStatus);
                    }
                });
        }
        return false;
    });
    $('#submitCategoryDetail').click(function () {
        $.ajax(
            {
                url: Config.updateUrl,
                type: "PUT",
                data: {goodsId: CONST_GLOBAL_GOODS_ID, goodsDetail: getContent()},
                dataType: "json",
                success: function (data, textStatus, jqXHR) {
                    toastr.success(data.msg, data.title);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    toastr.error(errorThrown, textStatus);
                }
            });
        return false;
    });

    $('#submitAttrLike').click(getAttrJson);


});


function getAttrJson() {
    if (typeof (CONST_GLOBAL_GOODS_ID) == "undefined") {
        alert("请先添加商品");
        return false;
    }
    var check_array = [];
    var json_string = [];
    var json_params = [];
    var json_real_price = [];
    $("input", $("#attribute-list")).each(function () {
        if ($(this).attr('name') == "attr-checkbox") {
            check_array.push($(this).prop("checked") ? 1 : 0);
            return;
        }
        if ($(this).attr('name') == "attr-text") {
            json_string.push(
                '"goodsId":' + CONST_GLOBAL_GOODS_ID + ',' +
                '"attrName":"' + $(this).attr("attrName") + '",' +
                '"attrId":' + $(this).attr("attrId") + ',' +
                '"attrValue":"' + $(this).attr("attrValue") + '",' +
                '"extraPrice":' + ($(this).val() == undefined || $(this).val() == '' ? 0 : $(this).val()));
            return;
        }
        if ($(this).attr('name') == "attrExtraPrice") {
            json_real_price.push(
                '"realExtraPrice":' + ($(this).val() == undefined || $(this).val() == '' ? 0 : $(this).val()) + ",");
            return;
        }


    });

    for (var i = 0; i < check_array.length; i++) {
        switch (i) {
            case 0:
                json_params.push('[{' + json_string[i] + ',' + json_real_price[i] + '"attr_show":' + check_array[i] + '},');
                break;
            case check_array.length - 1:
                json_params.push('{' + json_string[i] + ',' + json_real_price[i] + '"attr_show":' + check_array[i] + '}]');
                break;
            default:
                json_params.push('{' + json_string[i] + ',' + json_real_price[i] + '"attr_show":' + check_array[i] + '},');
                break;
        }
    }


    $.ajax(
        {
            url: ConfigAttributeLink.createUrl,
            type: "POST",
            data: {attrJson: json_params.join('').replace(/\n/g,'')},
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                toastr.success(data.msg, data.title);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });

    return false;
}


function getAttrList() {
    var id = $('#typeId option:selected').val()
    // if (id <= 0)
    //     return;
    $.ajax(
        {
            url: ConfigAttribute.selectUrl,
            type: "GET",
            dataType: "json",
            data: {typeId: id},
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                data.data.map(function (category) {
                    categories.push('<div class="form-group">');
                    categories.push('<label class="col-sm-2 control-label" id="' + category.attrId + '">' + category.attrName + '</label>');
                    categories.push('<div class="col-sm-10">');
                    var attrValues = category.attrValues.split('\n');
                    if (attrValues && attrValues.length > 0) {
                        for (var i = 0; i < attrValues.length; i++) {
                            categories.push('<div class="form-inline">');
                            categories.push('<div class="checkbox col-sm-2 control-label" >');
                            categories.push('<label>');
                            categories.push('<input name="attr-checkbox"  type="checkbox" value="">'+ attrValues[i]+'');
                            categories.push('</label>');
                            categories.push('</div>');
                            categories.push('<div class="form-group">');
                            categories.push('<div class="col-sm-10">');
                            categories.push('<input type="number" name="attr-text"   class="form-control"  attrName="' + category.attrName.replace('\n','') + '" attrId="' + category.attrId + '" attrValue="' + attrValues[i] + '" required="" aria-required="true" minlength="1" maxlength="100000">');
                            categories.push('</div>');
                            categories.push('</div>');

                            categories.push('<div class="form-group">');
                            categories.push('<div class="col-sm-10">');
                            categories.push('<input type="number" name="attrExtraPrice"   class="form-control" required="" aria-required="true" minlength="1" maxlength="100000">');
                            categories.push('</div>');
                            categories.push('</div>');

                            categories.push('</div>');
                        }
                    }
                    categories.push('</div>');
                    categories.push('</div>');
                });
                $("#attribute-list").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });

}

var CONST_GLOBAL_GOODS_ID;
function getContent() {
    return ue.getContent();
}

$(".goodsScreenPrice").change(function () {
    $(".profit").text(($(".goodsRealPrice").val() / $(".goodsScreenPrice").val()).toFixed(2) * 10);
});
$(".goodsRealPrice").change(function () {
    $(".profit").text(($(".goodsRealPrice").val() / $(".goodsScreenPrice").val()).toFixed(2) * 10);
});